import json

import requests
from django.contrib import messages
from django.core.paginator import Paginator
from django.http import HttpResponse
from django.shortcuts import redirect
from django.shortcuts import render
from django.template import Template, RequestContext
from django.views.generic.list import ListView

# Create your views here. 控制层
from common.models import Post


class PostList(ListView):
    model = Post
    paginate_by = 20
    context_object_name = 'posts'


def get_queryset(self):
    category = self.request.GET.get('category')
    keyword = self.request.GET.get('keyword')
    if category:
        return Post.objects.filter(category=category)
    elif keyword:
        return Post.objects.filter(title__contains=keyword)
    else:
        return Post.objects.all()


# class PostDetail(DetailView):
#     model = Post
#     context_object_name = 'post'
post_template = [None]


def post(request, pk):
    post = Post.objects.get(id=pk)
    if post_template[0] is None:

        query = Post.objects.values('category').distinct()
        categories = [item['category'] for item in query]
        context = {'post': post, "categories": categories}

        return render(request, 'post_detail.html', context)
    else:
        template = Template(post_template[0])
        context = RequestContext(request, {'post': post})
        return HttpResponse(template.render(context))


def recover(request):
    messages.warning(request, '已经恢复默认模板!')
    post_template[0] = None
    return redirect(request.META.get('HTTP_REFERER'))


def main(request):
    post_obj = Post.objects.all()  # 获取借书表中所有的数据

    paginator = Paginator(post_obj, 10)  # 实例化Paginator, 每页显示5条数据

    page = paginator.page(1)  # 传递当前页的实例对象到前端

    """
    主页
    """
    news = Post.objects.values()

    query = Post.objects.values('category').distinct()
    categories = [item['category'] for item in query]

    query = Post.objects.values('category').distinct()
    categories = [item['category'] for item in query]
    context = {"news": page, "categories": categories, "key1": "Search", "page": page}

    return render(request, 'home.html', context)

    # return HttpResponse(retStr)


def mypost(request):
    if request.method == 'POST':
        news = Post.objects.values()
        key = request.POST['post']
        news_request = requests.get("https://api.github.com/users/" + key)
        userapi = json.loads(news_request.content)
        return render(request, 'page.html', {'page': news})
    else:
        notfound = "请在搜索框中输入你需要查询的新闻..."

        query = Post.objects.values('category').distinct()
        categories = [item['category'] for item in query]
        context = {'notfound': notfound, "categories": categories, "key1": "Search"}

        return render(request, 'post.html', context)


def mypage(request, pindex):
    """
    分页查询
    """
    post_obj = Post.objects.all()  # 获取借书表中所有的数据

    paginator = Paginator(post_obj, 10)  # 实例化Paginator, 每页显示5条数据
    if pindex == "":  # django中默认返回空值，所以加以判断，并设置默认值为1
        pindex = 1
    else:  # 如果有返回在值，把返回值转为整数型
        int(pindex)

    query = Post.objects.values('category').distinct()
    categories = [item['category'] for item in query]


    page = paginator.page(pindex)  # 传递当前页的实例对象到前端
    context = {"page": page, "key": "Search", "categories": categories}
    return render(request, "page.html", context)


def pagesearch(request, pindex, key):
    """
    搜索分页查询
    """
    post_obj = Post.objects.filter(title__contains=key)  # 获取借书表中所有的数据

    paginator = Paginator(post_obj, 6)  # 实例化Paginator, 每页显示5条数据
    if pindex == "":  # django中默认返回空值，所以加以判断，并设置默认值为1
        pindex = 1
    else:  # 如果有返回在值，把返回值转为整数型
        int(pindex)
    page = paginator.page(pindex)  # 传递当前页的实例对象到前端
    context = {"page": page}
    return render(request, "page.html", context)


def search(request):
    """
    搜索查询
    """
    key = request.POST['key']
    post_obj = Post.objects.filter(title__contains=key)

    query = Post.objects.values('category').distinct()
    categories = [item['category'] for item in query]
    context = {"page": post_obj, "categories": categories, "key": key}

    return render(request, "page.html", context)


def myc(request):
    """
    分类搜索查询
    """
    key = request.GET['category']
    post_obj = Post.objects.filter(category__contains=key)

    context = {"page": post_obj, "categories": getcategories()}

    return render(request, "page.html", context)


def getcategories():
    query = Post.objects.values('category').distinct()
    categories = [item['category'] for item in query]
    return categories


def test(request):
    """
    测试
    """
    api = Post.objects.values()
    query = Post.objects.values('category').distinct()
    categories = [item['category'] for item in query]
    return render(request, "test.html", {"api": api, "categories": categories})


def home(request):
    """
    测试
    """
    api_request = requests.get("https://api.github.com/users?since=0")
    api = json.loads(api_request.content)
    news = Post.objects.all()

    return render(request, 'home.html', {"api": api})


def echarts(request):
    return render(request, "echarts.html", )